﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class BezierCurve
{
    public Vector3[] points;
    public float slope1;
    public float slope2;
    public delegate void ActDrawLine(Vector3 a, Vector3 b, Color color);
    public delegate void ActDrawPoint(Vector3 a, Color color);
    public static ActDrawLine drawLine;
    public static ActDrawPoint drawPoint;
    public static Color colorTrack;
    public static Color colorControlLines;
    public static Color colorPoints;
    public static int accuracy = 100;
    public BezierCurve()
    {
        this.points = new Vector3[4];
    }
    public BezierCurve(Vector3[] points)
    {
        this.points = points;
    }
    public float Length
    {
        get
        {
            float length = 0f;
            var prev = Evaluate(0);
            for (int i = 1; i < accuracy; i++)
            {
                var t = i / (float)accuracy;
                var curr = Evaluate(t);
                length += Vector3.Distance(curr, prev);
                prev = curr;
            }
            return length;
        }
    }
    public void DrawPoints()
    {
        drawPoint(points[0], colorPoints);
        drawPoint(points[1], colorPoints);
        drawPoint(points[2], colorPoints);
        drawPoint(points[3], colorPoints);

    }
    public void DrawLines()
    {
        drawLine(points[0], points[1], colorControlLines);
        drawLine(points[2], points[3], colorControlLines);
        var factor = 1f / accuracy;
        var prev = points[0];
        for (int i = 1; i < accuracy; i++)
        {
            var curr = Evaluate(i * factor);
            drawLine(prev, curr, colorTrack);
            prev = curr;
        }
    }
    public float Slope(float t)
    {
        return Mathf.Lerp(slope1, slope2, t);
    }
    public Vector3 Evaluate(float t)
    {
        var Points3 = new Vector3[3];
        for (int i = 0; i < 3; i++)
        {
            Points3[i] = Vector3.Lerp(points[i], points[i + 1], t);
        }
        var Points2 = new Vector3[2];
        for (int i = 0; i < 2; i++)
        {
            Points2[i] = Vector3.Lerp(Points3[i], Points3[i + 1], t);
        }
        return Vector3.Lerp(Points2[0], Points2[1], t);
    }
}
